package com.hobbit.ui.managers
{
	import flash.utils.Dictionary;

	/**
	 * 语言包
	 * @author 晓晔
	 * 
	 */	
	public class LanguageManager
	{
		
		//type
		public static const XML_TYPE:String = "xml";
		public static const JSON_TYPE:String = "json";
		
		//dic
		private var textDic:Dictionary;
		
		
		public function LanguageManager()
		{
			textDic = new Dictionary();
		}
		
		private static  var _instance:LanguageManager;
		
		public static  function getInstance():LanguageManager {
			if(!_instance)
				_instance = new LanguageManager();
			return _instance; 
		}
		
		/**
		 * 解析语言包(type:xml,json)
		 */
		public function parserLanguage(resource:*,type:String = "xml"):void	{
			if(resource)	
			{
				switch(type)
				{
					case LanguageManager.XML_TYPE:
						var xml:XML;
						if(resource is XML)	{
							xml = resource as XML;
						}else	{
							xml = new XML(resource.toString());
						}
						var xmlList:XMLList = xml.item;
						for each(var child:XML in xmlList)
						{
							var $key:String = child.key;
							var $text:String = child.value;
							textDic[$key] = $text;
						}
					break;
					case LanguageManager.JSON_TYPE:
						//todo
						//目前木有。。。
						break;
				}
			}
		}
		
		/**
		 *  取得一个文本
		 * @param resourceName 文字索引，如果库中找不到这个索引则直接使用resourceName
		 * @param parameters 替换的参数，用于替换{}中的内容
		 * @return 
		 */
		public function getText(resourceName:String,parameters:Array = null):String
		{
			var resourceStr:String;
			if(textDic[resourceName] != null)
			{
				resourceStr =  textDic[resourceName]
			}else{
				resourceStr = resourceName;
			}
			if (parameters)	{
				for (var j:int = 0, pLen:int = parameters.length; j < pLen; j++)	{
					var placeStr:String = "\\{" + j + "\\}";
					var re:RegExp = new RegExp(placeStr,"g");
					resourceStr = resourceStr.replace(re, parameters[j]);
				}
			}
			
			return resourceStr;
			
		}
		
	}
}